import React, { Component } from "react";
import {
  Form,
  Input,
  Button,
  DatePicker,
  Transfer,
  message,
  Tag,
  Radio,
  TimePicker,
  Tabs,
  List,
  Select,
} from "antd";
import moment from "moment";
import axios from "axios";
import qs from "qs";
import OrgTree from "./OrgTree";
import "../mock/user003001";
import "../mock/user003002";
import "../mock/user6363";
import "../mock/group";
import "../mock/groupMembers";
import "../mock/meetingdataById";
import "../mock/fechLeader";
const { TabPane } = Tabs;
const { Option } = Select;

/***
 *
 * getDataSource = { getDataSource };
 * record = { record };
 * page = { current };
 * rows = { rows };
 */
export default class EditTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      addVisible: false,
      //   mockData: ["李亮", "张明", "李飞", "王培"], //职工列表

      enableMockData: [], //职工列表
      enable: [], //外部数据
      isEnable: "",
      rules: [
        {
          required: true,
          message: "此项不可为空",
        },
      ],
      treeData: [],
      getDataSource: props.getDataSource,
      rowsData: {}, //当前会议数据
      personnelGroup: [], //人员组
      startTime: "00:00",
      endTime: "00:00",
      leaders: [], //所有领导数据
      selLeaders: [], //已选中的领导
      byId: false,
    };
    this.formRef = React.createRef();
    this.setTreeData = this.setTreeData.bind(this);
    this.treeOnSelect = this.treeOnSelect.bind(this);
  }

  /**添加参会人 */
  handleEnableChange = (enable) => {
    this.setState({ enable });
  };
  /**机构数据 */
  setTreeData = (treeData) => {
    setTimeout(() => {
      this.setState({ treeData });
    }, 0);
  };

  /*点击部门列表,展示部门人员 */
  treeOnSelect = (value) => {
    // console.log(value);
    // this.getMock(isHost, value);
    axios
      .get("../weekmeeting/searchUsers.rst?orgId=" + value[0])
      .then((res) => {
        let response = res.data;
        // response = response.data;
        // console.log(response);
        if (response.resultCode === 0) {
          let res = response.result.data;
          if (response.result.total === 0) {
            res = [];
          }
          /**清空并关闭添加表单 */

          this.setState({
            enableMockData: res.map((person) => {
              return {
                key: person.EMPID + "_" + person.EMPNAME,
                title: person.EMPID + "_" + person.EMPNAME,
              };
            }),
          });
        } else {
          // message.error("人员数据请求失败");
        }
      })
      .catch((error) => {
        message.error("人员数据请求失败");
      });
  };

  /**初始化数据 */
  initData = (row) => {
    let selLeaders = [];
    row.meetingLeaders.split(",").map((item) => {
      //处理已选择的领导
      selLeaders.push({ key: item });
      return null;
    });

    this.setState({
      rowsData: row,
      enable: row.enable, //外部数据
      addVisible: true, //*弹出,
      isEnable: row.isEnable === 1 ? "500px" : "0px",
      startTime: row.meetingTime,
      endTime: row.meetingEndTime,
      selLeaders: selLeaders,
    });
    // /**等待form渲染 */
    setTimeout(() => {
      this.formRef.current.setFieldsValue({
        address: row.meetingAddress,
        content: row.meetingContent,
        remark: row.remark,
        leaders: selLeaders,
        responsibleDepartment: row.responsibleDepartment,
        isEnable: row.enable.length > 0 ? "500px" : "0px",
      });

      /**手动添加必选样式（假） */
      var dateLable = document.querySelectorAll(
        ".ant-form-item-label label[for='add-meeting_date']"
      );
      var timeLable = document.querySelectorAll(
        ".ant-form-item-label label[for='add-meeting_time']"
      );

      dateLable.forEach((i) => i.classList.add("ant-form-item-required"));
      timeLable.forEach((i) => i.classList.add("ant-form-item-required"));
    }, 100);
  };

  // /**弹出对话框 */
  // showAddModal = () => {
  //   /**手动添加必填样式 */

  //   // const record = this.props.record;
  //   const selectedRowKeys = this.props.selectedRowKeys;
  //   if (selectedRowKeys.length < 1) {
  //     message.info("请选择要修改的数据");
  //   } else if (selectedRowKeys.length > 1) {
  //     message.info("每次只能修改一条数据");
  //   } else {
  //     this.props.dataSource.map((row) => {
  //       if (row.key === selectedRowKeys[0]) {
  //         // console.log(row);
  //         this.setState({
  //           rowsData: row,
  //           enable: row.enable, //外部数据
  //           addVisible: true, //*弹出,
  //           isEnable: row.enable.length > 0 ? "500px" : "0px",
  //           startTime: row.meetingTime,
  //           endTime: row.meetingEndTime,
  //         });
  //         // /**等待form渲染 */
  //         setTimeout(() => {
  //           this.formRef.current.setFieldsValue({
  //             address: row.meetingAddress,
  //             content: row.meetingContent,
  //             remark: row.remark,
  //             leaders: row.meetingLeaders,
  //             responsibleDepartment: row.responsibleDepartment,
  //             isEnable: row.enable.length > 0 ? "500px" : "0px",
  //           });

  //           /**手动添加必选样式（假） */
  //           var dateLable = document.querySelectorAll(
  //             ".ant-form-item-label label[for='add-meeting_date']"
  //           );
  //           var timeLable = document.querySelectorAll(
  //             ".ant-form-item-label label[for='add-meeting_time']"
  //           );

  //           dateLable.forEach((i) => i.classList.add("ant-form-item-required"));
  //           timeLable.forEach((i) => i.classList.add("ant-form-item-required"));
  //         }, 100);
  //       }
  //     });
  //   }
  // };

  onFinish = (values) => {
    /**表单字段在不做改动时返回时会为undefined，需要手动判断 */

    let pass = true;
    let enableData = "";
    let messCon = "";
    let isEnable = 0;
    /**表单返回值 currVal*/
    const currVal = this.formRef.current.getFieldsValue();
    console.log(currVal);
    // console.log(currVal)
    const date = document.getElementById("add-meeting_date");
    /**判断日期，地点，内容 */
    if (!currVal.address.length || !currVal.content.length) {
      pass = false;
      messCon = "活动地点及名称";
    }

    // if (this.state.enable.length === 0) {
    //   pass = false;
    //   messCon = "分享范围";
    // }
    if (this.state.isEnable !== "0px") {
      //分享
      enableData = this.state.enable.join();
      isEnable = 1;
    }
    // let meetingTime;
    // let meetingEndTime;
    // if (currVal.time) {
    //   meetingTime = currVal.time[0].format("HH:mm");
    //   meetingEndTime = currVal.time[1].format("HH:mm");
    // } else {
    //   meetingTime = this.state.rowsData.meetingTime;
    //   meetingEndTime = this.state.rowsData.meetingEndTime;
    // }

    /** */
    if (pass) {
      this.setState({ loading: true });
      /**修改活动数据 */

      axios({
        url: "../weekmeeting/updatemeeting.rst",
        method: "post",
        data: qs.stringify({
          id: this.state.rowsData.key,
          meetingDate: date.value.split(" ")[0],
          meetingTime: this.state.startTime,
          meetingEndTime: this.state.endTime,
          locale: currVal.address,
          theme: currVal.content,
          person: enableData,
          enable: isEnable,
          remark: currVal.remark,
          leaders:
            typeof currVal.leaders[0] == "string"
              ? currVal.leaders.join()
              : this.state.rowsData.meetingLeaders,
          responsibleDepartment: currVal.responsibleDepartment,
        }),
      })
        .then((res) => {
          let response = res.data;
          if (response.resultCode === 0) {
            /**清空并关闭添加表单 */
            message.success("提交成功");
            this.setState({ loading: false, addVisible: false });
            /**重新渲染活动列表 */
            if (!this.state.byId) {
              this.props.getDataSource();
            } else {
              if (window.parent) {
                //本页面作为iframe打开时，操作完成后关闭窗口
                // window.parent.closeWindow();
                var iframe = document.createElement("iframe");
                iframe.setAttribute(
                  "style",
                  "position:absolute;left:-9999999px;top:-999999px;"
                );
                iframe.setAttribute(
                  "src",
                  "https://portal.zjbti.net.cn/_web/customized/scheduleCenter/closeWindow.html"
                );
                document.body.appendChild(iframe);
              }
            }
          } else {
            message.error("提交失败");
          }
        })
        .catch((error) => {
          message.error("提交失败");
        });
    } else {
      /**有字段为空 */
      message.error(messCon + "字段不可为空！");
    }
  };

  handleCancel = () => {
    const { enable } = this.state.rowsData;
    /**清空修改表单状态 */
    // this.formRef.current.resetFields();
    this.setState({
      enable: enable,
    });
  };

  /** */
  getUrlParams = (name, str) => {
    const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`);
    const r = str.substr(1).match(reg);
    if (r != null) return decodeURIComponent(r[2]);
    return null;
  };

  componentDidMount() {
    this.getPersonnelGroup();
    // 调用父组件方法把当前实例传给父组件
    if (this.props.onRef) {
      this.props.onRef("EditTable", this);
    }

    /**获取领导组数据 */
    this.getLeadersData();

    /**url中含有id字段时，修改该id的会议*/
    // console.log(this.props.location);
    if (this.props.location) {
      let id = this.getUrlParams("id", this.props.location.search);
      if (id) {
        this.searchDataById(id);
      }
    }
  }

  getLeadersData = () => {
    /**获取领导组数据 */
    axios
      .get("../weekmeeting/fechLeader.rst")
      .then((res) => {
        let response = res.data;
        if (response.resultCode === 0) {
          this.setState({
            leaders: response.result.data,
          });
        } else {
          // alert('获取职工数据失败')
          message.error("领导组请求失败");
        }
      })
      .catch((error) => {
        // alert('获取职工数据失败')
        message.error("领导组请求失败");
      });
  };

  /** */
  searchDataById = (id) => {
    console.log(id);
    axios
      .post(
        "../weekmeeting/fetchweekmeeting.rst",
        qs.stringify({
          id: id,
          page: 1,
          rows: 1,
        })
      )
      .then((res) => {
        let response = res.data;
        console.log(response);
        if (response.resultCode === 0) {
          console.log(response.result.total);
          let data = response.result.data[0];
          console.log(data);
          let row = {
            key: data.id,
            isEnable: data.enable,
            enable: data.person.length === 0 ? [] : data.person.split(","),
            meetingKey: Number(0 + 1 + 1 * (1 - 1)),
            meetingDate: data.meetingDate,
            meetingTime: data.meetingTime,
            meetingEndTime: data.meetingEndTime,
            meetingAddress: data.locale,
            meetingContent: data.theme,
            meetingLeaders: data.leaders,
            // meetingJoin: data.participator.split(","),
            remark: data.remark,
            responsibleDepartment: data.responsibleDepartment,
          };
          console.log(row);
          this.initData(row);
          this.setState({ byId: true });
        } else {
          // alert('数据请求失败')
          // message.error("数据请求失败");
        }
      })
      .catch((error) => {
        console.log(error);
        // alert('数据请求失败')
        message.error("数据请求失败");
      });
  };

  /**关闭Tag */
  handleHostTagClose = (removedTag) => {
    const hostTargetKeys = this.state.hostTargetKeys.filter(
      (hostTargetKeys) => hostTargetKeys !== removedTag
    );
    // console.log(hostTargetKeys);
    this.setState({ hostTargetKeys });
  };
  handleEnableTagClose = (removedTag) => {
    const enable = this.state.enable.filter((enable) => enable !== removedTag);
    // console.log(enable);
    this.setState({ enable });
  };
  /*遍历插入Tag */
  hostForMap = (tag) => {
    // console.log(tag);
    return (
      <span key={tag} style={{ display: "inline-block", marginBottom: 16 }}>
        <Tag
          closable
          color="geekblue"
          onClose={(e) => {
            e.preventDefault();
            this.handleHostTagClose(tag);
          }}
        >
          {tag}
        </Tag>
      </span>
    );
  };
  enableForMap = (tag) => {
    // console.log(tag);
    return (
      <span key={tag} style={{ display: "inline-block", marginBottom: 16 }}>
        <Tag
          closable
          color="blue"
          onClose={(e) => {
            e.preventDefault();
            this.handleEnableTagClose(tag);
          }}
        >
          {tag}
        </Tag>
      </span>
    );
  };
  enableChange = (e) => {
    // console.log(e.target.value);
    this.setState({
      isEnable: e.target.value === 1 ? "500px" : "0px",
    });
  };

  /*获取人员组数据 */
  getPersonnelGroup = () => {
    axios
      .get("../weekmeeting/group.rst")
      .then((res) => {
        let response = res.data;
        // console.log(response);
        if (response.resultCode === 0) {
          let res = response.result.data;
          if (response.result.total === 0) {
            res = [];
          }
          /**清空并关闭添加表单 */
          this.setState({
            personnelGroup: res.map((group) => {
              return {
                label: group.groupName,
                value: group.groupName,
                groupId: group.groupId,
              };
            }),
          });
        } else {
          // message.error("人员组请求失败");
        }
      })
      .catch((error) => {
        message.error("人员组请求失败");
      });
  };

  /**选择人员组 */
  personnelGroupOnClick = (item) => {
    // console.log(item.member);
    axios
      .get("../weekmeeting/groupMembers.rst?groupId=" + item.groupId)
      .then((res) => {
        let response = res.data;
        // console.log(response);
        if (response.resultCode === 0) {
          let res = response.result.data;
          if (response.result.total === 0) {
            res = [];
          }
          /**清空并关闭添加表单 */
          this.setState({
            enableMockData: res.map((person) => {
              return {
                key: person.EMPID + "_" + person.EMPNAME,
                title: person.EMPID + "_" + person.EMPNAME,
              };
            }),
          });
        } else {
          // message.error("人员数据请求失败");
        }
      })
      .catch((error) => {
        message.error("人员数据请求失败");
      });
  };

  /**选择会议时段 */
  timeQuantumOnChange = (e) => {
    // console.log("radio checked", e.target.value);

    // eslint-disable-next-line default-case
    switch (e.target.value) {
      case 2:
        this.setState({
          startTime: "08:30",
          endTime: "17:30",
        });
        break;

      case 3:
        this.setState({
          startTime: "08:30",
          endTime: "11:30",
        });
        break;
      case 4:
        this.setState({
          startTime: "13:30",
          endTime: "17:00",
        });
        break;
      case 5:
        this.setState({
          startTime: "18:00",
          endTime: "20:30",
        });
        break;
    }
  };

  render() {
    const { loading } = this.state;
    /**添加活动数据 */

    const {
      rules,
      enableMockData,
      enable,
      treeData,
      personnelGroup,
      startTime,
      endTime,
      isEnable,
      leaders,
      selLeaders,
    } = this.state;
    const { meetingDate, key } = this.state.rowsData;
    /**参会人员 */
    const enableTag = enable.map(this.enableForMap);
    /**领导组数据 */
    const leadersOption = leaders.map((item) => {
      return <Option key={item.id + "_" + item.name}>{item.name}</Option>;
    });

    console.log(selLeaders);

    // console.log(this.state.rowsData);

    return (
      <>
        <Form
          key={key}
          name="add-meeting"
          onFinish={this.onFinish}
          className="search-meet"
          ref={this.formRef}
        >
          <Form.Item name="date" label="日期" shouldUpdate>
            <DatePicker
              format="YYYY-MM-DD"
              defaultValue={moment(meetingDate, "YYYY-MM-DD")}
            />
          </Form.Item>
          <Form.Item name="content" label="事件内容" rules={rules}>
            <Input />
          </Form.Item>

          <Form.Item name="address" label="地点" rules={rules}>
            <Input />
          </Form.Item>
          <Form.Item
            name="startTime"
            label="开始时间"
            rules={rules}
            initialValue={moment(startTime, "HH:mm")}
            // key={startTime}
          >
            <TimePicker
              key={startTime}
              defaultValue={moment(startTime, "HH:mm")}
              format="HH:mm"
              value={moment(startTime, "HH:mm")}
              onChange={(time, timeString) =>
                this.setState({ startTime: timeString })
              }
            />
            <input hidden={true} value={startTime} />
          </Form.Item>
          <Form.Item
            name="endTime"
            label="结束时间"
            rules={rules}
            initialValue={moment(endTime, "HH:mm")}
            // key={startTime}
          >
            <TimePicker
              key={endTime}
              defaultValue={moment(endTime, "HH:mm")}
              format="HH:mm"
              value={moment(endTime, "HH:mm")}
              onChange={(time, timeString) =>
                this.setState({ endTime: timeString })
              }
            />
            <input hidden={true} value={endTime} />
          </Form.Item>
          <Form.Item name="timeQuantum" label="">
            <Radio.Group onChange={this.timeQuantumOnChange} value={1}>
              {/* <Radio value={1}>无</Radio> */}
              <Radio value={2}>全天</Radio>
              <Radio value={3}>上午</Radio>
              <Radio value={4}>下午</Radio>
              <Radio value={5}>晚上</Radio>
            </Radio.Group>
          </Form.Item>

          {/* <Form.Item name="time" label="时间">
             
              <TimePicker.RangePicker
                format="HH:mm"
                // defaultValue={moment([meetingTime, meetingEndTime], "HH:mm")}
                defaultValue={[
                  moment(meetingTime, "HH:mm"),
                  moment(meetingEndTime, "HH:mm"),
                ]}
              />
            </Form.Item> */}
          <Form.Item name="responsibleDepartment" label="责任部门">
            <Input />
          </Form.Item>
          <Form.Item name="leaders" label="出席领导" rules={rules}>
            <Select
              mode="multiple"
              allowClear
              style={{ width: "100%" }}
              placeholder="请选择"
              // defaultValue={[{ key: "003_李青" }, { key: "004_蔚" }]}
              defaultValue={selLeaders}
              // onChange={handleChange}
              // options={this.props.leaders}
            >
              {leadersOption}
            </Select>
          </Form.Item>
          <Form.Item name="remark" label="备注">
            <Input />
          </Form.Item>
          <Form.Item name="enable" label="是否分享">
            <Radio.Group
              key={isEnable}
              name="enable"
              onChange={this.enableChange}
              defaultValue={isEnable === "500px" ? 1 : 0}
            >
              <Radio key={isEnable} value={1}>
                分享
              </Radio>
              <Radio key={isEnable} value={0}>
                不分享
              </Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item
            name="enable"
            label="分享范围"
            className="enableSelect"
            style={{ maxHeight: this.state.isEnable }}
          >
            {enableTag}
            <Tabs
              defaultActiveKey="1"
              type="card"
              size="small"
              className="OrgTreeTab"
            >
              <TabPane tab="人员机构" key="1">
                <OrgTree
                  treeData={treeData}
                  setTreeData={this.setTreeData}
                  treeOnSelect={this.treeOnSelect}
                  isHost={false}
                />
              </TabPane>
              <TabPane tab="人员组" key="2">
                <List
                  className="personnelGroup"
                  size="small"
                  itemLayout="horizontal"
                  dataSource={personnelGroup}
                  renderItem={(item) => (
                    <List.Item>
                      <List.Item.Meta
                        title={item.value}
                        member={item.member}
                        onClick={() => this.personnelGroupOnClick(item)}
                      />
                    </List.Item>
                  )}
                />
              </TabPane>
            </Tabs>

            <Transfer
              dataSource={enableMockData}
              targetKeys={enable}
              // selectedKeys={enableTargetKeys}
              showSearch
              listStyle={{
                width: 250,
                height: 200,
              }}
              operations={["添加", "移出"]}
              onChange={this.handleEnableChange}
              render={(item) => item.title}
            />
          </Form.Item>

          <Button type="primary" htmlType="submit" loading={loading}>
            确定
          </Button>
        </Form>
      </>
    );
  }
}
